<template>
    <el-form :model="form">
        <el-form-item label="登录账号" :label-width="formLabelWidth">
            <el-input disabled v-model="form.adminname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth">
            <el-input type="password" v-model="form.password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色" :label-width="formLabelWidth">
            <el-select v-model.number="form.role" placeholder="请选择角色">
                <el-option v-for="item in roles" v-bind:label="item.label" v-bind:value="item.value" />
            </el-select>
        </el-form-item>
        <el-form-item label="权限" :label-width="formLabelWidth">
            <!-- <el-input v-model="form.checkedKeys" autocomplete="off" /> -->
            <el-tree ref="treeRef" :data="data" show-checkbox node-key="id" />
        </el-form-item>
        <el-form-item>
            <el-button @click="editOperFn">修改</el-button>
            <el-button @click="cancelFn">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue';
import type { IOper } from "@/myTypes"
import { getOperDetailApi,editOperatorApi } from "@/api/user"
import { ElMessage, ElTree } from "element-plus";
import { roles,grantsData as data } from "./data";
import type { TreeKey } from 'element-plus/es/components/tree/src/tree.type.mjs';

interface IProps {
    editadminname: string
}

const props = defineProps<IProps>();

interface IEmits {
    (e: "onOk"): void,
    (e: "onCancel"): void,
}
const emits = defineEmits<IEmits>();


// 一、获取管理员详情并初始化界面

const treeRef = ref<InstanceType<typeof ElTree>>();

const form = reactive<IOper>({
    adminname: '',
    password: "",
    role: 0,
    checkedKeys: [],
    adminid: ""
})

// 获取管理员详情
const getAdminDetailFn = () => {
    console.log("获取管理员详情");
    getOperDetailApi(props.editadminname).then(res => {
        if (res.data.code === "200") {
            form.adminname = res.data.data[0].adminname
            form.password = res.data.data[0].password
            form.role = res.data.data[0].role
            form.checkedKeys = res.data.data[0].checkedKeys;

            // 单独处理checkedKeys;
            // form.checkedKeys;
            
            const checkedKeys = filterCheckedKeys(form.checkedKeys);

            treeRef.value?.setCheckedKeys(checkedKeys);
            // treeRef.value?.setCheckedKeys(["1","2","2-1","2-1-1","4","4-1","4-2","4-4"]);

            // ? 表示如果该属性有值，才调用后面的方法
            // ！表示前面的数据一定有值。即：断言该数据不为空。
        }
    })
}

// 过滤父级的checkedKeys
function filterCheckedKeys(checkedKeys: TreeKey[]):TreeKey[] {

    const arr:TreeKey[] = [];
    
    checkedKeys.forEach(item => { //"1"
        // 判断数组（checkedKeys）中是否存在 以 item-开头的元素，如果没有说明item是叶子节点。把itempush到arr。
        if(!checkedKeys.some(sonItem=>(sonItem as string).startsWith(item as string+"-"))){
            arr.push(item);
        }
    })

    console.log("arr",arr);
    
    return arr;

    // const arr:string[] = [];
    // // 只找带 - 。把该项的首位（第一个 - 前面的删除掉）
    // // 1）、拿出所有带 - 的首位的数组 ["2","4","4","4"]
    // checkedKeys.forEach(item => {
    //     if((item as string).includes("-")){
            
    //         arr.push((item as string).slice(0,(item as string).indexOf("-")));

    //     }
    // })

    // console.log("arr",arr);
    // // 2、删除所有带 - 的首位。
    // return checkedKeys.filter(item=>!arr.includes(item as string));
   
}

watch(props, () => {
    getAdminDetailFn();
}, {
    immediate: true
})



const formLabelWidth = '140px'

// 修改管理员信息
const editOperFn = () => {
    const checkedKeys = (treeRef.value?.getCheckedKeys() || []);
    const halfCheckedKeys = (treeRef.value?.getHalfCheckedKeys() || []);

    form.checkedKeys = [...checkedKeys, ...halfCheckedKeys];

    editOperatorApi(form).then(res => {
        if (res.data.code === "200") {
            ElMessage({
                message: '修改成功',
                type: 'success',
                duration: 1000
            })
            // 1、清空数据
            // form.adminname = '';
            // form.password = '';
            // form.role = 0;
            // form.checkedKeys = [];

            // 2、关闭当前窗口
            emits("onOk");

        } else {
            ElMessage({
                message: '添加失败',
                type: 'error',
                duration: 1000
            })
        }
    }).catch(err => {
        console.log("添加操作人员时，服务器出错：err", err)
    });
}

const cancelFn = () => {
    emits("onCancel");
}


const defaultProps = {
    children: 'children',
    label: 'label',
}


</script>


<style lang="scss" scoped>
.el-select {
    width: 300px;
}

.el-input {
    width: 300px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>
